import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
const storageMembers = "members_storage";
const storageKeys = {
  week: "storageWeekName",
  day: "storageDayName",
};
const storageNormals = {
  week: 8,
  day: 50,
};
export default new Vuex.Store({
  state: {},
  mutations: {
    saveMembers(state, data) {
      let members = data;
      localStorage.setItem(storageMembers, JSON.stringify(members));
    },
    saveStorage(state, { tag, num }) {
      let key = storageKeys[tag];
      let num1 = localStorage.getItem(key);
      if (num1) {
        if (typeof num1 === "string") {
          num1 = parseInt(num1);
        }
      }
      if (!num1 || num > num1) {
        num1 = num;
      }
      localStorage.setItem(key, num1);
    },
  },
  getters: {
    getMembers: (state) => () => {
      let str = localStorage.getItem(storageMembers);
      if (str) {
        let list = JSON.parse(str);
        if (list.length > 0 && !list[0].no) {
          for (let i = 0, n = list.length; i < n; i++) {
            list[i].no = i + 1;
          }
          localStorage.setItem(storageMembers, JSON.stringify(list));
        }
        return list;
      }
      return [];
    },
    getQQObj: (state, getters) => () => {
      let members = getters.getMembers();
      let obj = {};
      for (let i = 0, n = members.length; i < n; i++) {
        let item = members[i];
        obj[item.qq] = item;
      }
      return obj;
    },
    getNickNameObj: (state, getters) => () => {
      let members = getters.getMembers();
      let obj = {};
      for (let i = 0, n = members.length; i < n; i++) {
        let item = members[i];
        obj[item.nickname] = item;
      }
      return obj;
    },
    getStorageVal: (state) => (tag) => {
      let key = storageKeys[tag];
      let num = localStorage.getItem(key);
      if (num) {
        if (typeof num === "string") {
          num = parseInt(num);
        }
      }
      if (!num) {
        num = storageNormals[tag];
      }
      return num;
    },
  },
  actions: {},
  modules: {},
});
